package hr.mlab.app.expenses.activities.type;

import hr.mlab.app.expenses.AppGlobals;
import hr.mlab.app.expenses.DatabaseOpenHelper;
import hr.mlab.app.expenses.R;
import hr.mlab.app.expenses.widgets.mLabSpinner;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.SpinnerAdapter;

public class TypeList extends ListActivity {
    private EditText searchText;
    private SQLiteDatabase db;
    private Integer categoryId;
    private Integer groupId;
    private Integer typeId;
    private Cursor typeCursor;
    private ListAdapter typeAdapter;
    private Boolean fromItemClick=false;
    private mLabSpinner categorySpinner;
    private Cursor categoryCursor;
    private SpinnerAdapter categoryAdapter;
    private mLabSpinner groupSpinner;
    private Cursor groupCursor;
    private SpinnerAdapter groupAdapter;
    
    /** Called when the activity is first created. */
    @Override    
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	setContentView(R.layout.typelist);
    	db = (new DatabaseOpenHelper(this)).getReadableDatabase();

    	searchText = (EditText) findViewById (R.id.searchText);
    	categorySpinner = (mLabSpinner) findViewById(R.id.spnCategory);
    	groupSpinner = (mLabSpinner) findViewById(R.id.spnGroup);
    	
    	categorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parent, View itemSelected, 
            						   int selectedItemPosition, long selected) {
            	fillGroupSpinner();
            	fillListView();
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
            	fillGroupSpinner();
            	fillListView();
            }

    	}); 
    	
    	groupSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parent, View itemSelected, 
            						   int selectedItemPosition, long selected) {
            	fillListView();
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
            	fillListView();
            }

    	}); 
    	
    	fillCategorySpinner();
    	fillGroupSpinner();
    	fillListView();
    }

    /**
     * Closing activity
     */
    @Override    
    public void onDestroy() {
    	super.onDestroy();
    	typeCursor.close();
    	db.close();
    }

    /**
     * On button search click
     * @param view
     */
    public void searchClick(View view) {
    	fillListView();
    }

    /**
     * Filling list
     * @param view
     */
    public void fillListView() {
    	groupId = (int) groupSpinner.getSelectedItemId();
    	
    	typeCursor = db.rawQuery("SELECT _id, typeName FROM " + DatabaseOpenHelper.dbTypes + " as t " +
								 " left outer join " +  DatabaseOpenHelper.dbTypeGroups + " as tg" +
								 " on t._id = tg.typeId WHERE tg.groupId = ? and typeName LIKE ? order by typeName", 
								 new String[]{groupId.toString(), "%" + searchText.getText().toString().trim() + "%"});

        typeAdapter = new SimpleCursorAdapter(
                            this, 
                            R.layout.typerow, 
                            typeCursor, 
                            new String[] {"typeName"}, 
                            new int[] {R.id.typeName});

        setListAdapter(typeAdapter);
        
        registerForContextMenu(getListView());
    }

    /**
     * Filling category spinner
     * 
     */
    public void fillCategorySpinner() {
    	categoryCursor = db.query(DatabaseOpenHelper.dbCategories, 
    						   new String[]{"_id", "categoryName"}, 
    						   null, null, null, null, null);

    	startManagingCursor(categoryCursor);
	
		categoryAdapter = new SimpleCursorAdapter(
						  this, 
						  android.R.layout.simple_spinner_item, 
						  categoryCursor, 
						  new String[] { "categoryName" },
						  new int[] { android.R.id.text1 });
		
		categorySpinner.setAdapter(categoryAdapter);
    }

    /**
     * Filling group spinner
     * 
     */
    public void fillGroupSpinner() {
    	categoryId = (int) categorySpinner.getSelectedItemId();
    	
    	groupCursor = db.rawQuery("SELECT _id, groupName FROM " + DatabaseOpenHelper.dbGroups + " as g" +
				 				  " left outer join " +  DatabaseOpenHelper.dbGroupCategories + " as gc" +
				 				  " on g._id = gc.groupId WHERE gc.categoryId = ?", 
				 				  new String[]{categoryId.toString()});    			

    	startManagingCursor(groupCursor);
	
		groupAdapter = new SimpleCursorAdapter(
						  this, 
						  android.R.layout.simple_spinner_item, 
						  groupCursor, 
						  new String[] { "groupName" },
						  new int[] { android.R.id.text1 });
		
		groupSpinner.setAdapter(groupAdapter);
    }

    /**
     * Catcher of list clicks
     * @param ListView parent, View view, int position, long id
     */
    public void onListItemClick(ListView parent, View view, int position, long id) {
    	typeId = (int) id;
    	fromItemClick = true;
    	((Activity) this).openOptionsMenu();
    }
    
 	/**
 	 * Menu initialization
 	 * @param menu
 	 */
 	@Override
 	public boolean onCreateOptionsMenu(Menu menu) {
 		MenuInflater inflater = getMenuInflater();
 		inflater.inflate(R.menu.newmenu, menu);
 		return true;
 	}
 	
 	/**
 	 * Changing a menu. We don't have fixed menu. It's changed depending on where it opens 
 	 * @param menu
 	 */
 	@Override
 	public boolean onPrepareOptionsMenu(Menu menu) {
 		menu.clear();
 		if(fromItemClick) {
 			menu.add(0, AppGlobals.optUpdate, 0, this.getString(R.string.btnUpdate));
 			menu.add(0, AppGlobals.optDetail, 0, this.getString(R.string.btnDetail));
 			menu.add(0, AppGlobals.optDelete, 0, this.getString(R.string.btnDelete));
 			menu.add(0, AppGlobals.optGroup, 0, this.getString(R.string.group));
 			menu.add(0, AppGlobals.optImport, 0, this.getString(R.string.group_import));
 		} else {
 			menu.add(0, AppGlobals.optNew, 0, this.getString(R.string.btnNew));
 		}

 		fromItemClick = false;
 		
 		return super.onPrepareOptionsMenu(menu);
 	}

 	/**
 	 * Reaction to the menu selection
 	 * @param featureId, menuItem
 	 */
 	@Override
 	public boolean onMenuItemSelected(int featureId, MenuItem item) {
 		return super.onMenuItemSelected(featureId, item);
 	}

 	/**
 	 * Reaction to the option menu selection
 	 * @param menuItem
 	 */
 	@Override
 	public boolean onOptionsItemSelected(MenuItem item) {
		callGroupDetail(item.getItemId());
 		return super.onOptionsItemSelected(item);
 	}
 	
 	/**
 	 * Reaction to the context menu selection
 	 * @param menuItem
 	 */
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		callGroupDetail(item.getItemId());
		return super.onContextItemSelected(item);
	}

	/**
	 * we need a handler when the secondary activity finishes it's work
	 * and returns control to this activity...
	 * @param requestCode, resultCode, intent
	 */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent){
    	super.onActivityResult(requestCode, resultCode, intent);
    	if(resultCode == Activity.RESULT_OK ) { 
    		fillListView();
    		setSelection(intent.getIntExtra("groupId", 0));
    	}
    }

    /**
     * Calling detail for category
     * @param menuitem - indicates option
     */
	public void callGroupDetail(int menuItem){
		if(menuItem == AppGlobals.optGroup) {
	    	Intent intent = new Intent(this, TypeGroupList.class);
	    	intent.putExtra("typeId", typeId);
	    	
	    	startActivityForResult(intent, menuItem);
		} else {
	    	Intent intent = new Intent(this, TypeDetail.class);
	    	intent.putExtra("option", (byte) menuItem);
	    	intent.putExtra("categoryId", (int) categorySpinner.getSelectedItemId());
	    	intent.putExtra("groupId", (int) groupSpinner.getSelectedItemId());
	    	
	    	if(menuItem > 1) {
	    		intent.putExtra("typeId", typeId);
	    	} else {
	    		intent.putExtra("typeId", 0);
	    	}
	    	
	    	startActivityForResult(intent, menuItem);
		}
	}
}
